<template>
    <div class="art-full-height">
        <ElCard class="art-table-card" shadow="never" :style="{ 'margin-top': showSearchBar ? '12px' : '0' }">
            <div class="header">
                提现设置
            </div>
            <el-tabs v-model="tableLayout" class="demo-tabs" @tab-click="handleTabChange">
                <el-tab-pane label="微信" name="1">
                    <el-form :model="settingForm" label-width="120" :rules="rules">
                        <el-form-item label="真实姓名：" prop="wxName">
                            <el-input v-model="settingForm.wxName" placeholder="请输入微信姓名"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号：" prop="wxPhone">
                            <el-input v-model="settingForm.wxPhone" placeholder="请输入手机号"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="微信收款码：" prop="wxImage">
                            <el-upload class="avatar-uploader" :action="server" :headers="headers"
                                :show-file-list="false" :on-success="(response) => handleAvatarSuccess('wx', response)"
                                :before-upload="beforeAvatarUpload">
                                <el-image v-if="settingForm.wxImage" :src="settingForm.wxImage" class="avatar"
                                    fit="contain"></el-image>
                                <i class="el-icon-plus avatar-uploader-icon" v-else>
                                    <el-icon :size="40">
                                        <Plus />
                                    </el-icon>
                                </i>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="支付宝" name="2">
                    <el-form :model="settingForm" label-width="120" :rules="rules">
                        <el-form-item label="真实姓名：" prop="zfbName">
                            <el-input v-model="settingForm.zfbName" placeholder="请输入真实姓名"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="支付宝账号：" prop="zfbAccount">
                            <el-input v-model="settingForm.zfbAccount" placeholder="请输入支付宝账号"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="支付宝收款码：" prop="zfbImage">
                            <el-upload class="avatar-uploader" :action="server" :headers="headers"
                                :show-file-list="false" :on-success="(response) => handleAvatarSuccess('zfb', response)"
                                :before-upload="beforeAvatarUpload">
                                <el-image v-if="settingForm.zfbImage" :src="settingForm.zfbImage" class="avatar"
                                    fit="contain"></el-image>
                                <i class="el-icon-plus avatar-uploader-icon" v-else>
                                    <el-icon :size="40">
                                        <Plus />
                                    </el-icon>
                                </i>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="银行卡" name="3">
                    <el-form :model="settingForm" label-width="120" :rules="rules">
                        <el-form-item label="真实姓名：" prop="cardName">
                            <el-input v-model="settingForm.cardName" placeholder="请输入真实姓名"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="所属银行：" prop="cardBank">
                            <el-input v-model="settingForm.cardBank" placeholder="请输入所属银行"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="所属支行：" prop="subBranch">
                            <el-input v-model="settingForm.subBranch" placeholder="请输入所属支行"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="银行卡卡号：" prop="cardId">
                            <el-input v-model="settingForm.cardId" placeholder="请输入银行卡卡号"
                                style="width: 300px;"></el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
            <el-button type="primary" class="save" v-ripple @click="submit">
                保存
            </el-button>
        </ElCard>
    </div>
</template>
<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus'
import { updateWithdrawalMethod, getWithdrawalMethod } from '@/api/agent'
import type { TabsPaneContext } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const settingForm = reactive({
    wxName: '',
    wxPhone: '',
    zfbName: '',
    zfbAccount: '',
    cardName: '',
    cardId: '',
    cardBank: '',
    subBranch: '',
    bankType: '',
    wxImage: '',
    zfbImage: '',
    // 为不同提现方式分别维护各自的 ID；用于判断新增/编辑
    wxBankId: '',
    zfbBankId: '',
    cardBankId: ''
})

const showSearchBar = ref(false)
const tableLayout = ref('1')
const rules = computed<FormRules>(() => ({
    wxName: [{ required: true, message: '请输入微信姓名', trigger: 'blur' }],
    wxPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    zfbName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    zfbAccount: [{ required: true, message: '请输入支付宝', trigger: 'blur' }],
    cardName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    cardBank: [{ required: true, message: '请输入所属银行', trigger: 'blur' }],
    // subBranch: [{ required: true, message: '请输入所属支行', trigger: 'blur' }],
    cardId: [{ required: true, message: '请输入银行卡卡号', trigger: 'blur' }],
    wxImage: [{ required: true, message: '请上传微信收款码', trigger: 'change' }],
    zfbImage: [{ required: true, message: '请上传支付宝收款码', trigger: 'change' }],
}))

let server = `${import.meta.env.VITE_API_URL}files`
let { accessToken } = userStore
const headers = { Authorization: 'Brokerage ' + accessToken }

const handleTabChange = (e: any) => {
    tableLayout.value = e.index
}


const filterEmptyValues = (obj: any) => {
    const result: any = {}
    for (const key in obj) {
        if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
            result[key] = obj[key]
        }
    }
    return result
}

const submit = async () => {
    let obj: any = {
        bankType: tableLayout.value === '1' ? '01' : tableLayout.value === '2' ? '02' : '03',
        accountName: tableLayout.value === '1' ? settingForm.wxName : tableLayout.value === '2' ? settingForm.zfbName : settingForm.cardName,
        accountNo: tableLayout.value === '1' ? settingForm.wxPhone : tableLayout.value === '2' ? settingForm.zfbAccount : settingForm.cardId,
        bankName: tableLayout.value === '3' ? settingForm.cardBank : '',
        bankCode: '',
        branchName: tableLayout.value === '3' ? settingForm.subBranch : '',
        qrCodeUrl: tableLayout.value === '1' ? settingForm.wxImage : tableLayout.value === '2' ? settingForm.zfbImage : '',
        isDefault: 0,
        idCardNo: '',
        phone: '',
        bankStatus: 1

    }
    // 根据当前 tab 的不同，选择对应的 bankId；新增时为空则不传
    const currentBankId = tableLayout.value === '1' ? settingForm.wxBankId : tableLayout.value === '2' ? settingForm.zfbBankId : settingForm.cardBankId
    if (currentBankId) {
        obj.bankId = currentBankId
    }
    const res = await updateWithdrawalMethod(filterEmptyValues(obj))
    if (res.code === '0') {
        ElMessage.success('保存成功')
        getData()
    }
}

const handleAvatarSuccess = (type: string, file: any) => {
    if (type === 'wx') {
        settingForm.wxImage = file.data.url
    } else {
        settingForm.zfbImage = file.data.url
    }
}
//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
    const isLt2M = file.size / 10240 / 10240 < 2
    if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
        ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 20MB!!')
        return false
    }
}

const getData = async () => {
    const res = await getWithdrawalMethod()
    if (res.code === '0' && Array.isArray(res.data)) {
        // 先清空表单
        settingForm.wxName = ''
        settingForm.wxPhone = ''
        settingForm.wxImage = ''
        settingForm.zfbName = ''
        settingForm.zfbAccount = ''
        settingForm.zfbImage = ''
        settingForm.cardName = ''
        settingForm.cardId = ''
        settingForm.cardBank = ''
        settingForm.subBranch = ''
        settingForm.wxBankId = ''
        settingForm.zfbBankId = ''
        settingForm.cardBankId = ''

        // 遍历所有提现方式，分别根据 bankType 回填字段
        res.data.forEach(info => {
            if (info.bankType === '01') {
                // 微信
                settingForm.wxName = info.accountName || ''
                settingForm.wxPhone = info.accountNo || ''
                settingForm.wxImage = info.qrCodeUrl || ''
                settingForm.wxBankId = info.id || ''
            } else if (info.bankType === '02') {
                // 支付宝
                settingForm.zfbName = info.accountName || ''
                settingForm.zfbAccount = info.accountNo || ''
                settingForm.zfbImage = info.qrCodeUrl || ''
                settingForm.zfbBankId = info.id || ''
            } else if (info.bankType === '03') {
                // 银行卡
                settingForm.cardName = info.accountName || ''
                settingForm.cardId = info.accountNo || ''
                settingForm.cardBank = info.bankName || ''
                settingForm.subBranch = info.branchName || ''
                settingForm.cardBankId = info.id || ''
            }
        })
    }
}

onMounted(() => {
    getData()
})
</script>
<style lang="scss" scoped>
.header {
    margin-bottom: 20px;
    font-size: 25px;
}

.art-table-card {
    :deep(.el-form) {
        height: 300px;
    }

    .save {
        width: 90px;
        margin-left: 120px;
        margin-top: 100px;
    }
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;

    .mask {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 24px;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s ease;
        color: #fff;
        font-size: 12px;
    }

    .del-image {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        color: #8c939d;
    }

    &:hover .mask {
        opacity: 1;
    }

    &:hover .del-image {
        display: block;
    }
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>